package com.wan.net.core.websocket;

import com.wan.net.core.packet.Packet;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import io.netty.handler.codec.http.websocketx.WebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
/**
 * @author wwh
 * @date 2022/6/16 14:57
 */
public class WebsocketCodec extends MessageToMessageCodec<WebSocketFrame, Packet> {
    private final Logger log = LoggerFactory.getLogger(this.getClass());


    @Override
    protected void encode(ChannelHandlerContext context, Packet pack, List<Object> list) throws Exception {
        Channel channel = context.channel();
        try {
            ByteBuf byteBuf = context.alloc().ioBuffer();
            pack.write(byteBuf);
            list.add(new BinaryWebSocketFrame(byteBuf));
        } catch (Exception e) {
            log.error("WebsocketCodec encode exception异常!channel:{},pack:{}", channel, pack, e);
            throw e;
        } catch (Throwable e) {
            log.error("WebsocketCodec encode Throwable异常!channel:{},pack:{}", channel, pack, e);
            throw e;
        }
    }

    @Override
    protected void decode(ChannelHandlerContext context, WebSocketFrame webSocketFrame, List<Object> out) throws Exception {
        if (webSocketFrame instanceof BinaryWebSocketFrame) {
            Channel channel = context.channel();
            try {
                ByteBuf byteBuf = webSocketFrame.content();
                Packet packet = new Packet();
                if(packet.read(byteBuf)) out.add(packet);
            } catch (Exception e) {
                log.error("WebsocketCodec decode exception异常!{}", channel, e);
                throw e;
            } catch (Throwable e) {
                log.error("WebsocketCodec decode Throwable异常!{}", channel, e);
                throw e;
            }
            return;
        }
        log.warn("WebSocketFrame frame type = {}, channel={}", webSocketFrame.getClass(), context.channel());
    }
}
